package com.emergency.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.emergency.config.BusinessException;
import com.emergency.constant.ResponseConfirmConstant;
import com.emergency.constant.ResponseStatusConstant;
import com.emergency.data.entity.AddressBook;
import com.emergency.data.entity.Department;
import com.emergency.data.entity.DepartmentConfirmRecording;
import com.emergency.data.entity.EmergencyRecording;
import com.emergency.data.param.StartResponseParam;
import com.emergency.data.result.DeptConfirmRecordingResult;
import com.emergency.data.vo.CurrentLevelVO;
import com.emergency.data.vo.DepartmentConfirmVO;
import com.emergency.data.vo.DeptConfirmVO;
import com.emergency.http.DefaultResponseCode;
import com.emergency.mapper.*;
import com.emergency.service.EmergencyRecordingService;
import com.emergency.util.SMSUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * (EmergencyPointSupplies)部门应急响应确认记录服务实现类
 *
 * @author makejava
 * @since 2020-10-10
 */
//@Slf4j
@Service
public class EmergencyRecordingServiceImpl extends ServiceImpl<EmergencyRecordingMapper, EmergencyRecording> implements EmergencyRecordingService {

    @Resource
    private EmergencyRecordingMapper emergencyRecordingMapper;

    @Resource
    private DepartmentConfirmRecordingMapper departmentConfirmRecordingMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private DepartmentLinkmanMapper departmentLinkmanMapper;

    @Resource
    private AddressBookMapper addressBookMapper;

    @Override
    public List<List<String>> dataStatistics() {
        //返回集合
        List<List<String>> dataList = new ArrayList<>();
        //查询条件
        QueryWrapper<EmergencyRecording> query = new QueryWrapper<>();
        query.groupBy("year");
        query.orderByAsc("year");
        List<EmergencyRecording> yearList = emergencyRecordingMapper.selectList(query);
        if (CollUtil.isNotEmpty(yearList)) {
            //启始年份
            Integer start = yearList.get(0).getYear();
            //结束年份
            Integer end = yearList.get(yearList.size() - 1).getYear();
            for (int i = start; i <= end; i++) {
                List<String> data = new ArrayList<>();
                data.add(String.valueOf(i));
                for (int level = 4; level >= 1; level--) {
                    //查询对应级别响应次数
                    Integer count = emergencyRecordingMapper.selectCount(new QueryWrapper<EmergencyRecording>()
                            .eq("grade", level)
                            .eq("year", i));
                    data.add(String.valueOf(count));
                }
                dataList.add(data);
            }
        }
        return dataList;
    }

    @Override
    public CurrentLevelVO getCurrentLevel() {
        //返回VO
        CurrentLevelVO vo = new CurrentLevelVO();
        //查询条件
        QueryWrapper<EmergencyRecording> query = new QueryWrapper<>();
        query.eq("status", ResponseStatusConstant.START);
        query.last("LIMIT 1");
        EmergencyRecording recording = emergencyRecordingMapper.selectOne(query);
        if (recording == null) {
            vo.setStatus(0);
        } else {
            BeanUtil.copyProperties(recording, vo);
        }
        return vo;
    }

    @Override
    public DeptConfirmVO deptConfirmList() {
        //返回对象VO
        DeptConfirmVO vo = new DeptConfirmVO();
        //查询有无正在启动的应急响应
        EmergencyRecording recording = emergencyRecordingMapper.selectOne(new QueryWrapper<EmergencyRecording>()
                .eq("status", ResponseStatusConstant.START)
                .last("LIMIT 1"));
        //部门响应数据列表
        List<DeptConfirmRecordingResult> confirmRecordingList
                = departmentConfirmRecordingMapper.deptConfirmList(recording == null ? null : recording.getId());
        //县级部门
        List<DepartmentConfirmVO> countyDeptList = new ArrayList<>();
        //镇级部门
        List<DepartmentConfirmVO> townDeptList = new ArrayList<>();
        //村级部门
        List<DepartmentConfirmVO> villageDeptList = new ArrayList<>();
        for (DeptConfirmRecordingResult result : confirmRecordingList) {
            DepartmentConfirmVO confirmVO = new DepartmentConfirmVO();
            BeanUtil.copyProperties(result, confirmVO);
            if(result.getDeptLevel() == null){
                continue;
            }
            switch (result.getDeptLevel()) {
                case 0:
                    countyDeptList.add(confirmVO);
                    break;
                case 1:
                    townDeptList.add(confirmVO);
                    break;
                case 2:
                    villageDeptList.add(confirmVO);
                    break;
            }
        }
        vo.setCountyDeptList(countyDeptList);
        vo.setTownDeptList(townDeptList);
        vo.setVillageDeptList(villageDeptList);
        return vo;
    }

    @Override
    public void start(StartResponseParam param) {
        //查询有无正在启动的应急响应
        EmergencyRecording emergencyRecording = emergencyRecordingMapper.selectOne(new QueryWrapper<EmergencyRecording>()
                .eq("status", ResponseStatusConstant.START)
                .last("LIMIT 1"));
        if (emergencyRecording != null) {
            throw new BusinessException(DefaultResponseCode.EMERGENCY_RESPONSE_IS_START);
        }
        EmergencyRecording recording = new EmergencyRecording();
        recording.setGrade(param.getGrade());
        recording.setYear(LocalDate.now().getYear());
        emergencyRecordingMapper.insertAndReturnId(recording);
        //生成部门响应确认记录
        createDepartmentConfirmRecording(param, recording);
    }

    @Override
    public void change(StartResponseParam param) {
        //查询当前正在响应的应急记录
        EmergencyRecording emergencyRecording = emergencyRecordingMapper.selectOne(new QueryWrapper<EmergencyRecording>()
                .eq("status", ResponseStatusConstant.START)
                .last("LIMIT 1"));
        if (emergencyRecording != null) {
            //解除当前正在响应的应急记录
            emergencyRecording.setStatus(ResponseStatusConstant.REMOVE);
            emergencyRecordingMapper.updateById(emergencyRecording);
        }
        //生成新的应急响应记录
        EmergencyRecording recording = new EmergencyRecording();
        recording.setGrade(param.getGrade());
        recording.setYear(LocalDate.now().getYear());
        emergencyRecordingMapper.insertAndReturnId(recording);
        //生成部门响应确认记录
        createDepartmentConfirmRecording(param, recording);
    }

    @Override
    public void stop(Long id) {
        EmergencyRecording recording = emergencyRecordingMapper.selectById(id);
        if (recording == null) {
            throw new BusinessException(DefaultResponseCode.EMERGENCY_RESPONSE_IS_NOT_EXIST);
        }
        recording.setStatus(ResponseStatusConstant.REMOVE);
        emergencyRecordingMapper.updateById(recording);
    }

    @Override
    public void confirmRecording(Long id) {
        DepartmentConfirmRecording recording = departmentConfirmRecordingMapper.selectById(id);
        if (recording == null) {
            throw new BusinessException(DefaultResponseCode.EMERGENCY_RESPONSE_CONFIRM_IS_NOT_EXIST);
        }
        recording.setIsConfirm(ResponseConfirmConstant.CONFIRMED);
        departmentConfirmRecordingMapper.updateById(recording);
    }

    @Value("${serverUrl}")
    private String serverUrl;

    private void createDepartmentConfirmRecording(StartResponseParam param, EmergencyRecording recording) {
        //部门ID列表
        List<Long> deptIdList = new ArrayList<>();
        deptIdList.addAll(param.getCountyDepIdList());
        deptIdList.addAll(param.getTownDepIdList());
        deptIdList.addAll(param.getVillageDepIdList());
        for (Long deptId : deptIdList) {
            DepartmentConfirmRecording confirmRecording = new DepartmentConfirmRecording();
            confirmRecording.setDeptId(deptId);
            //查询部门信息
            Department department = departmentMapper.selectOne(new QueryWrapper<Department>()
                    .eq("id", deptId)
                    .last("LIMIT 1"));
            if (department != null) {
                confirmRecording.setDeptLevel(department.getLevel());
            }
            confirmRecording.setRecordingId(recording.getId());
            departmentConfirmRecordingMapper.insertAndReturnId(confirmRecording);
            //发送短信通知到部门
            // 查询部门相关联系人
            addressBookMapper.selectList(new QueryWrapper<AddressBook>()
                    .eq("dept_id", deptId)).forEach(c -> {
                //联系方式
                String phone = c.getPhone();
                //联系地址
                String url = serverUrl + "/emergency/response/confirmRecording?id=" + confirmRecording.getId();
                //发送短息
                boolean res = SMSUtil.sendStartResponseSMS(phone, recording.getGrade(), url);
//                if (!res) {
//                    log.info("向部门 id 为 {} ，联系人为 {}，手机号为 {} 发送短信失败......", deptId, c.getName(), phone);
//                } else {
//                    log.info("链接地址为： {}", url);
//                }
            });
        }
    }
}
